package org.restoran.service.parser.jackson;

import org.codehaus.jackson.map.ObjectMapper;
import org.restoran.service.parser.Parser;

import java.io.IOException;
import java.io.Writer;
import java.util.Collection;

/**
 * @author Snisar Bogdan.
 */
public class PersistableBeanSerializer implements Parser {

    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public PersistableBeanSerializer() {}

    public PersistableBeanSerializer(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private ObjectMapper objectMapper;
    

    @Override
    public <E> String toJson(E entity) {
        try {
            return objectMapper.writeValueAsString(entity);  //To change body of implemented methods use File | Settings | File Templates.
        } catch (IOException e) {
            throw new ParsingDeserializException(e);
        }
    }

    @Override
    public <E> void toJson(Writer writer, E entity) {
        try {
            objectMapper.writeValue(writer, entity);  //To change body of implemented methods use File | Settings | File Templates.
        } catch (IOException e) {
            throw new ParsingDeserializException(e);
        }    }

    @Override
    public <E> String toJson(Collection<E> objects) {
        try {
            return objectMapper.writeValueAsString(objects);  //To change body of implemented methods use File | Settings | File Templates.
        } catch (IOException e) {
            throw new ParsingDeserializException(e);
        }    }

    @Override
    public <E> void toJson(Writer writer, Collection<E> args) {
        try {
            objectMapper.writeValue(writer, args);  //To change body of implemented methods use File | Settings | File Templates.
        } catch (IOException e) {
            throw new ParsingDeserializException(e);
        }    }

    @Override
    public <E> E fromJson(String json, Class<E> type) {
        try {
            return objectMapper.readValue(json, type);  //To change body of implemented methods use File | Settings | File Templates.
        } catch (IOException e) {
            throw new ParsingDeserializException(e);
        }    }

}
